# 导入必要的库
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
import matplotlib.pyplot as plt

# 1. 读取数据
data_path = r"D:\python\Binary classification\Logistic Regression\cs-training.csv"  # 请替换为您的数据路径
data = pd.read_csv(data_path)

# 2. 数据预处理
# 假设目标列名是 'target'1，特征列是其他所有列。如果您的数据不同，请根据实际情况修改。
data = data.dropna()
X = data.drop(columns=['SeriousDlqin2yrs'])  # 选择特征列
y = data['SeriousDlqin2yrs']  # 目标变量

# 3. 数据集拆分
# 将数据分为训练集和测试集（80%训练，20%测试）
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 4. 特征缩放
# 逻辑回归模型对特征的尺度比较敏感，因此进行标准化处理
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

# 5. 构建并训练逻辑回归模型
model = LogisticRegression()
model.fit(X_train, y_train)

# 6. 预测和评估模型
y_pred = model.predict(X_test)

# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print(f"模型准确率: {accuracy:.2f}")

# 输出混淆矩阵
print("混淆矩阵:")
print(confusion_matrix(y_test, y_pred))

# 输出分类报告（包括精确度、召回率等）
print("分类报告:")
print(classification_report(y_test, y_pred))

# 7. 绘制混淆矩阵图
cm = confusion_matrix(y_test, y_pred)
fig, ax = plt.subplots()
cax = ax.matshow(cm, cmap='Blues')
fig.colorbar(cax)
ax.set_xticklabels([''] + ['Negative', 'Positive'])
ax.set_yticklabels([''] + ['Negative', 'Positive'])
plt.xlabel('Predicted')
plt.ylabel('True')
plt.title('Confusion Matrix')
plt.show()
